﻿using System;
using System.Net;
using System.Net.Sockets;

namespace HGPFramework
{
    public class HGPNetwork
    {
        /// <summary>
        ///     Using server pool.ntp.org
        /// </summary>
        /// <returns></returns>
        public static bool HasServer()
        {
            try
            {
                IPHostEntry i = Dns.GetHostEntry("pool.ntp.org");
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        ///     using option server
        /// </summary>
        /// <param name="server">ex: hogiaphat.com.vn</param>
        /// <returns></returns>
        public static bool HasServer(string server)
        {
            try
            {
                IPHostEntry i = Dns.GetHostEntry(server);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        ///     Check Time from internet
        /// </summary>
        /// <returns></returns>
        public static DateTime GetNetworkTime()
        {
            const string ntpServer = "pool.ntp.org";
            var ntpData = new byte[48];
            ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)

            IPAddress[] addresses = Dns.GetHostEntry(ntpServer).AddressList;
            var ipEndPoint = new IPEndPoint(addresses[0], 123);
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            socket.Connect(ipEndPoint);
            socket.Send(ntpData);
            socket.Receive(ntpData);
            socket.Close();

            ulong intPart = (ulong) ntpData[40] << 24 | (ulong) ntpData[41] << 16 | (ulong) ntpData[42] << 8 |
                            ntpData[43];
            ulong fractPart = (ulong) ntpData[44] << 24 | (ulong) ntpData[45] << 16 | (ulong) ntpData[46] << 8 |
                              ntpData[47];

            ulong milliseconds = (intPart*1000) + ((fractPart*1000)/0x100000000L);
            DateTime networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long) milliseconds);

            return networkDateTime;
        }
    }
}